import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
import { ElMessage, ElLoading } from "element-plus";
import { ILoadingInstance } from "element-plus/lib/el-loading/src/loading.type";

export interface ResProps<T = unknown> {
  config: { url: string; method: string; data: string };
  data: T;
  headers: {
    ["content-length"]: string;
    ["content-type"]: string;
    ["Authorization"]: string;
  };
  status: number;
  statusText: string;
  statusCode: number;
}

export class Request {
  instance: AxiosInstance;
  loading: ILoadingInstance | undefined;
  showLoading: boolean;
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    this.showLoading = true;
    //全局拦截
    this.instance.interceptors.request.use(
      (result) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: "正在请求数据。。。。",
            background: "rgba(0,0,0,0.5)",
          });
        }
        this.showLoading = true;
        return result;
      },
      (error) => {
        this.loading && this.loading.close();
        this.showLoading = true;
      }
    );
    this.instance.interceptors.response.use(
      (result) => {
        this.loading && this.loading.close();
        this.showLoading = true;
        return result;
      },
      (err) => {
        this.loading && this.loading.close();
        this.showLoading = true;
        return err;
      }
    );
  }
  async get<T = unknown>(url: string, params = {}, showLoading = true) {
    const res: ResProps<T> = await this.instance.get(url, params);
    this.showLoading = showLoading;
    return res;
  }
  async post<T = unknown>(url: string, data = {}, params = {}, showLoading = true) {
    const res: ResProps<T> = await this.instance.post(url, data, params);
    this.showLoading = showLoading;
    return res;
  }

  async delete<T = unknown>(url: string, params = {}, showLoading = true) {
    const res: ResProps<T> = await this.instance.delete(url, params);
    this.showLoading = showLoading;
    return res;
  }

  async put<T = unknown>(url: string, data = {}, params = {}, showLoading = true) {
    const res: ResProps<T> = await this.instance.put(url, data, params);
    this.showLoading = showLoading;
    return res;
  }

  //全局拦截器

  // //内部就是promise.all
  // async all<T = any>(...args: (()=>Promise<ResProps<T>>)[]){
  //   const res: ResProps<T>[] = await Promise.all(args)

  // }
}
